<?php
namespace dgwht\ file;
use OSS\OssClient;

class Oss {

	public $Msg;
	private $Bucket;
	private $SecretId;
	private $SecretKey;
	private $Endpoint;
	private $Key = null;
	private $OSS;

	function __construct( $config = [] ) {
		//AccessKey ID
        $this->SecretId = isset($config['appid']) ? $config['appid'] : '';
		//AccessKey Secret
        $this->SecretKey = isset($config['appkey']) ? $config['appkey'] : '';
		//储存桶
        $this->Bucket = isset($config['bucket']) ? $config['bucket'] : '';
		//地域
        $region = isset($config['region']) ? $config['region'] : 'hangzhou';
		$this->Endpoint = "http://oss-cn-{$region}.aliyuncs.com";
		$this->OSS = new OssClient( $this->SecretId, $this->SecretKey, $this->Endpoint );
	}

	public function up( $key, $srcPath, $headers ) {
		$this->Key = $key;
		try {
			if(isset($headers)){
				$options = [
					OssClient::OSS_HEADERS => $headers,
				];
			}
			$ret = $this->OSS->uploadFile( $this->Bucket, $key, $srcPath, $options );
			if(!isset($ret['info']['url'])){
				$this->Msg = "上传失败";
				return false;
			}
		} catch ( \Exception $e ) {
			$this->Msg = $e;
			return false;
		}
		$this->Msg = "OK";
		return true;
	}
	
	public function getSignUrl($time, $key){
		if($key==null) $key = $this->Key;
		if($key==null) return false;
		try {
			$signedUrl = $this->OSS->signUrl($this->Bucket, $key, $time);
			return $signedUrl;
		} catch ( \Exception $e ) {
			return false;
		}
	}
	
	public function del($key){
		if(!is_array($key)) $key = [$key];
		try {
			$this->OSS->deleteObjects($this->Bucket, $key);
			return true;
		} catch ( \Exception $e ) {
			return false;
		}
	}

}